package cn.lyjuan.payment.third.base.pay.chl.impl.ali.util;

import cn.lyjuan.base.util.SpringUtils;
import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliChlCnf;
import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliNotifyReq;
import cn.lyjuan.payment.third.base.pay.enums.SimpleChlEnum;
import cn.lyjuan.payment.third.base.pay.enums.SimpleStatusEnum;
import cn.lyjuan.payment.third.base.pay.util.CertUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;

/**
 * 支付宝手机端SDK支付响应通知工具
 * Created by ly on 2015/2/4.
 */
@Service("alipaySDKNotify")
public class AlipayNotify {
    /**
     * 从Request中解析出通知请求信息
     *
     * @param req
     * @return
     */
    public static AliNotifyReq parseNotifyParams(HttpServletRequest req) {
        Map<String, String> resultMap = SpringUtils.getParam(req);

        AliNotifyReq params = new AliNotifyReq();

        params.putAll(resultMap);

        return params;
    }

    /**
     * 支付宝手机SDK异步通知验证签名是否正确
     *
     * @param params
     * @return
     */
    public static boolean veryfyNotifySign(Map<String, String> params, AliChlCnf cnf) {
        try {
            String path = CertUtil.getPrefixPath(cnf.getCertPath()) + SimpleChlEnum.ALI.name().toLowerCase() + "/alipayCertPublicKey_RSA2.crt";
            return AlipaySignature.rsaCertCheckV1(params, path, params.get("charset"), params.get("sign_type"));

            // RSA 验签
            //return AlipaySignature.rsa256CheckContent(signStr, params.get("sign"), cnf.getAliRsaPub(), PayConst.CHARSET);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 支付宝异步通知响应
     *
     * @param receiveSucc 是否返回接收通知成功
     * @return
     */
    public static String notifyRes(boolean receiveSucc) {
        return receiveSucc ? "success" : "fail";
    }

    /**
     * 异步通知信息中的交易状态
     *
     * @param params
     * @return
     */
    public static String notifyPayStatus(AliNotifyReq params) {
        // 解析交易状态
        return params.get("trade_status");
    }

    /**
     * 从异步通知中解析交易状态
     *
     * @param params 支付渠道的交易状态
     * @return
     */
    public static SimpleStatusEnum parseNotifyPayStatus(AliNotifyReq params) {
        // 成功
        if ("TRADE_SUCCESS".equalsIgnoreCase(notifyPayStatus(params)))
            return SimpleStatusEnum.SUCC;

        return SimpleStatusEnum.UNKNOWN;
    }

    /**
     * 从通知信息中获取支付平台交易号
     *
     * @param req
     * @return
     */
    public static String parseTranNoFromNotify(AliNotifyReq req) {
        return req.get("trade_no");
    }


}
